package com.pi.wms.service;



import com.pi.common.CodesConstants;
import com.pi.core.service.UserAccessUtils;
import com.pi.framework.core.util.ConvertUtils;
import com.pi.framework.core.util.SecurityUtils;
import com.pi.framework.core.util.StringUtils;
import com.pi.framework.pro.IGenericRepository;
import com.pi.pro.xcmg.am.common.XcmgAmConstants;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.common.WmsTextUtils;
import com.pi.wms.entity.TwaDocAsnDetails;
import com.pi.wms.entity.TwaDocAsnHeader;
import com.pi.wms.entity.TwmBasCustomer;
import com.pi.wms.entity.TwmBasMaterial;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;


@Service("WMSSMASNSERVICE")
@Transactional
@Slf4j
public class SmAsnService extends BaseAsnService<TwaDocAsnHeader, Long>{

	//@Autowired
	//protected AsnRepository repository;

	@Override
	protected IGenericRepository<TwaDocAsnHeader,Long> getRepository() {
		return this.repository;
	}

	@Override
	protected Predicate toPredicate(Root<TwaDocAsnHeader> root, CriteriaQuery<?> cq, CriteriaBuilder cb, Map<String, ?> query) {
		List<Predicate> list = new ArrayList<Predicate>();
		
		//this.toPredicateTextLike(root, cq, cb, query, "documentNumber", list);
		this.toPredicateSelectEquals(root, cq, cb, query, "type", list);
		this.toPredicateSelectEquals(root, cq, cb, query, "status", list);

        this.extPredicate(list, root, cq, cb, query);

		String docno = (String) query.get("no");
		if (!StringUtils.isNullOrBlank(docno)) {
			list.add(cb.or(cb.like(root.get("documentNumber"), "%" + docno + "%"), cb.like(root.get("refDocNumber"), "%" + docno + "%")));
		}
        String category = (String) query.get("category");
        if (!StringUtils.isNullOrBlank(category)) {
            list.add(cb.equal(root.get("category"), category.trim().toUpperCase()));
        }

		String material = (String) query.get("material");
        if (!StringUtils.isNullOrBlank(material)) {
            Join<TwaDocAsnDetails, TwmBasMaterial> materialJoin = root.join("details").join("material");
            list.add(cb.or(cb.like(materialJoin.get("code"), "%" + material.trim() + "%"), cb.like(materialJoin.get("name"), "%" + material.trim() + "%")));
		}

        String suplier = (String) query.get("suplier");
        if (!StringUtils.isNullOrBlank(suplier)) {
            suplier=suplier.trim();
            list.add(cb.or(cb.like(root.get("supplierCode"), "%" + suplier + "%"), cb.like(root.get("supplierName"), "%" + suplier + "%")));
        }

        //配盘单号
        String shipnumber = (String) query.get("deliveryshipnumber");
        if (!StringUtils.isNullOrBlank(shipnumber)) {
            list.add(cb.or(cb.like(root.get("deliveryShipNum"), "%" + shipnumber.trim() + "%")));
        }

        //批次
        String deliveryterms = (String) query.get("deliveryterms");
        if (!StringUtils.isNullOrBlank(deliveryterms)) {
            list.add(cb.and(cb.like(root.get("deliveryTerms"), "%" + deliveryterms.trim() + "%")));
        }

        //产线
        String unloadplace = (String) query.get("planunloadplace");
        if (!StringUtils.isNullOrBlank(unloadplace)) {
            list.add(cb.and(cb.like(root.get("planUnloadPlace"), "%" + unloadplace.trim() + "%")));
        }

        //工位
        String unloaddoor = (String) query.get("planunloaddoor");
        if (!StringUtils.isNullOrBlank(unloaddoor)) {
            list.add(cb.and(cb.like(root.get("planUnloadDoor"), "%" + unloaddoor.trim() + "%")));
        }

        //配盘点
        String deliveryfromplace = (String) query.get("deliveryfromplace");
        if (!StringUtils.isNullOrBlank(deliveryfromplace)) {
            list.add(cb.and(cb.like(root.get("deliveryFromPlace"), "%" + deliveryfromplace.trim() + "%")));
        }

        //容器编号
        String containnumber = (String) query.get("containnumber");
        if (!StringUtils.isNullOrBlank(containnumber)) {
            list.add(cb.and(cb.like(root.get("deliveryContainerNum"), "%" + containnumber.trim() + "%")));
        }

        //
        Date date=null;
        String fromdate = (String) query.get("fromdate");
        if (!StringUtils.isNullOrBlank(fromdate)) {
            date = WmsTextUtils.plainDate(fromdate,true);
            if (date!=null){
                list.add(cb.greaterThanOrEqualTo(root.get("createdDate"), date));
            }
        }
        String todate = (String) query.get("todate");
        if (!StringUtils.isNullOrBlank(todate)) {
            date = WmsTextUtils.plainDate(todate,false);
            if (date!=null){
                list.add(cb.lessThanOrEqualTo(root.get("createdDate"), date));
            }
        }

        //
        String[] incltypes = ConvertUtils.convertToStringArray(query.get("includeTypes"));
        List<String> indoctypes=null;
        if (incltypes != null) {
            indoctypes = Arrays.asList(incltypes);
            if (indoctypes != null && indoctypes.size() > 0) {
                Predicate p = root.get("type").in(indoctypes);
                list.add(cb.and(p));
            }
        }
        String[] excltypes = ConvertUtils.convertToStringArray(query.get("excludeTypes"));
        List<String> exdoctypes=null;
        if (excltypes != null) {
            exdoctypes = Arrays.asList(excltypes);
            if (exdoctypes != null && exdoctypes.size() > 0) {
                Predicate p = root.get("type").in(exdoctypes);
                list.add(cb.and(cb.not(p)));
            }
        }

        //页面选择
        Long divisionid= UserAccessUtils.getCurrentDivision();
        if ((divisionid!=null) && (divisionid>0L)){
            list.add(cb.equal(root.get("divisionId"), divisionid));
        }
        //权限控制
        List<Long> userDivisionIds = this.userDivisionService.findIdsByUsersId(SecurityUtils.getLoginUserId());
        if ((userDivisionIds!=null)&&(userDivisionIds.size()>0)){
            Predicate p = root.get("divisionId").in(userDivisionIds);
            list.add(cb.and(p));
        }

		//默认条件
		//list.add(cb.lessThan(root.get("status"), WmsConstants.ASN_STATUS_CANCELL));
        String option=CodesConstants.COMMON_FLAG_NO;
		if (query.get(WmsConstants.DOCUMENT_QUERY_OPTION)!=null){
            option=(String)query.get(WmsConstants.DOCUMENT_QUERY_OPTION);
            option=option.trim();
        }
        String status = (String) query.get("status");
        if ( (status!=null) &&
                ((WmsConstants.SO_STATUS_CLOSE.equalsIgnoreCase(status))||(WmsConstants.SO_STATUS_CANCELL.equalsIgnoreCase(status)))){
            option= WmsConstants.DOCUMENT_QUERY_OPTION_SHOWALL;
        }
        if (!option.equalsIgnoreCase(WmsConstants.DOCUMENT_QUERY_OPTION_SHOWALL)){
            list.add(cb.notEqual(root.get("status"), WmsConstants.ASN_STATUS_CLOSE));
            list.add(cb.notEqual(root.get("status"), WmsConstants.ASN_STATUS_CANCELL));
        }
		Predicate[] p = new Predicate[list.size()];
		return cb.and(list.toArray(p));
	}

	@Override
    protected void preSave(TwaDocAsnHeader asn){
		if (asn==null){
			return;
		}
		if (!asn.isNew()){
			return;
		}
		//
		if (asn.getGlobalClientId()==null){
            asn.setGlobalClientId(wmsClientConfig.globalClientid());
        }
        if (asn.getCustomerId()==null){
			asn.setCustomerId(wmsClientConfig.customerid());
		}

        if (asn.getDivisionId()==null){
            asn.setDivisionId(wmsClientConfig.divisionid());
        }
		//
        String docnum="";
		if (StringUtils.isNullOrBlank(asn.getDocumentNumber())){
            docnum=sequenceService.next(WmsConstants.SEQUENCE_NAME_DOC_ASN);
            if (StringUtils.isNullOrBlank(docnum)){
                docnum= WmsTextUtils.genTransNumber("A","");
            }
            asn.setDocumentNumber(docnum);
		}
		//
		if (asn.getSupplierId()!=null){
			Optional<TwmBasCustomer> su =customerRepository.findById(asn.getSupplierId());
			if (su.get()!=null){
				asn.setSupplierCode(su.get().getCode());
				asn.setSupplierName(su.get().getName());
			}
		}
		asn.setDelFlag(false);
		asn.setEditable(true);
		asn.setEnabled(true);
		asn.setCategory(XcmgAmConstants.WORK_SOURCE_SELF_MADE);

		//Status=0000
		Map<String,String> defValues=new HashMap<String,String>();
		defValues.put("type", WmsConstants.ASN_TYPE_WORK_ORDER);
		defValues.put("status", WmsConstants.ASN_STATUS_CREATE);
		defValues.put("qcStatus", WmsConstants.QUALITY_STATUS_PASS);
		defValues.put("releaseStatus", CodesConstants.COMMON_RELEASE_STATUS_CREATED);
		defValues.put("printStatus", CodesConstants.COMMON_FLAG_NO);
		StringUtils.ifNull(asn, defValues);
    }


}
